package com.yxy.service;

import com.github.pagehelper.PageHelper;
import com.yxy.base.BusinessException;
import com.yxy.dao.TableReceptionMapper;
import com.yxy.dto.TableReceptionDto;
import com.yxy.dto.TableSetMealDetailDto;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.model.TableReception;
import com.yxy.model.TableSetMealDetail;
import com.yxy.utils.TokenCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.realm.JDBCRealm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class TableReceptionService {

  @Autowired
  private TokenCheckUtil tokenCheckUtil;
  @Resource
  private TableReceptionMapper tableReceptionMapper;


  //添加方法（保存）
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public TableReception save(TableReceptionDto pojo) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    //BeanUtils.copyProperties("转换前的类", "转换后的类");
    BeanUtils.copyProperties(pojo, entity);
    entity.setCreateDate(new Date());
    entity.setCreateUserId(adminUser.getAdminUser().getId());
    entity.setCreateUserName(adminUser.getAdminUser().getUsername());
    tableReceptionMapper.insertSelective(entity);
    return entity;
  }

  //app添加方法（保存）
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public TableReception appSave(TableReceptionDto pojo) throws BusinessException {
//    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy-MM-dd");
    //BeanUtils.copyProperties("转换前的类", "转换后的类");
    BeanUtils.copyProperties(pojo, entity);

    try{
      entity.setStartTime(simpleDateFormat.parse(pojo.getStartTimeStr()));
      entity.setDayTime(simpleDateFormatDay.format(simpleDateFormatDay.parse(pojo.getStartTimeStr())));
    }catch (ParseException pe){
      pe.printStackTrace();
    }

    entity.setCreateDate(new Date());
    entity.setCreateUserId(pojo.getId());
    entity.setCreateUserName(pojo.getUserAccount());
    try{
      tableReceptionMapper.insertSelective(entity);
    }catch (Exception e){
      throw new BusinessException(455,"当天已有预约，请勿重复预约");
    }
    return entity;
  }


  //获取列表
  public List<TableReception> getlist(TableReceptionDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();

    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<TableReception> dbResult = tableReceptionMapper.selectList(query);

    TableReceptionDto tableReceptionDto = new TableReceptionDto();

    for(int i= 0;i<dbResult.size();i++){
      Date date = new Date();
      long nowDate = date.getTime();
      long receptionDate = dbResult.get(i).getStartTime().getTime();
      //判断是否预约过期

      if(receptionDate<=nowDate&&dbResult.get(i).getPerformAppoint()==0&&dbResult.get(i).getReceptionCancel()==0){
        tableReceptionDto.setId(dbResult.get(i).getId());
        tableReceptionDto.setPerformAppoint(2l);
        this.modify(tableReceptionDto);
      }
    }
    return dbResult;
  }


  //获取该医生的预约号码总数
  public Long getReservationsDayListCount(TableReceptionDto query) throws BusinessException {
    Long count = tableReceptionMapper.getReservationsDayListCount(query);
    return count;
  }


  //获取列表
  public List<TableReception> getReservationsDayList(TableReceptionDto query) throws BusinessException {
    List<TableReception> dbResult = tableReceptionMapper.getReservationsDayList(query);
    return dbResult;
  }
  //获取列表
  public List<TableReception> getReservationsOverList(TableReceptionDto query) throws BusinessException {
    List<TableReception> dbResult = tableReceptionMapper.getReservationsOverList(query);
    return dbResult;
  }

  //获取列表
  public List<TableReception> getListReceptionOutcome1(TableReceptionDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();

    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    query.setReceptionOutcome(1l);
    List<TableReception> dbResult = tableReceptionMapper.selectList(query);

    TableReceptionDto tableReceptionDto = new TableReceptionDto();

    for(int i= 0;i<dbResult.size();i++){
      Date date = new Date();
      long nowDate = date.getTime();
      long receptionDate = dbResult.get(i).getStartTime().getTime();
      //判断是否预约过期

      if(receptionDate<=nowDate&&dbResult.get(i).getPerformAppoint()==0&&dbResult.get(i).getReceptionCancel()==0){
        tableReceptionDto.setId(dbResult.get(i).getId());
        tableReceptionDto.setPerformAppoint(2l);
        this.modify(tableReceptionDto);
      }
    }
    return dbResult;
  }




  //获取列表
  public List<TableReception> getListByDay(TableReceptionDto query) throws BusinessException {
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    // 处理tenant id list
    Set<Long> tenantIdList = new HashSet<>();

    PageHelper.startPage(query.getPageNumber(), query.getPageSize());
    PageHelper.orderBy("t1.create_date desc");//排序
    List<TableReception> dbResult = tableReceptionMapper.getListByDay(query);
    return dbResult;
  }


  //获取列表
  public List<TableReception> appGetReception(TableReceptionDto query) throws BusinessException {
    List<TableReception> dbResult = tableReceptionMapper.appGetReception(query);
    for(int i= 0;i<dbResult.size();i++){
      Date date = new Date();
      long nowDate = date.getTime();
      long receptionDate = dbResult.get(i).getStartTime().getTime();
      //判断是否预约过期

      if(receptionDate<=nowDate&&dbResult.get(i).getPerformAppoint()==0){
        dbResult.get(i).setPerformAppoint(2l);
      }
    }
    return dbResult;
  }



  public List<TableReception> appGetPhysicianTimeOver(TableReceptionDto query) throws BusinessException {

    // 处理tenant id list
      Set<Long> tenantIdList = new HashSet<>();


    SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy-MM-dd");
    //BeanUtils.copyProperties("转换前的类", "转换后的类");


    try{

      query.setDayTime(simpleDateFormatDay.format(simpleDateFormatDay.parse(query.getStartTimeStr())));
    }catch (ParseException pe){
      pe.printStackTrace();
    }

    List<TableReception> dbResult = tableReceptionMapper.selectList(query);
    return dbResult;
  }



  public List<TableReception> checkPhysicianTime(TableReceptionDto query) throws BusinessException {
    SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy-MM-dd");
    try{

      query.setDayTime(simpleDateFormatDay.format(simpleDateFormatDay.parse(query.getDayTime())));
    }catch (ParseException pe){
      pe.printStackTrace();
    }

    List<TableReception> dbResult = tableReceptionMapper.selectCheckList(query);

    return dbResult;
  }


  //编辑数据（更新）
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public TableReception modify(TableReceptionDto pojo)throws BusinessException
  {
    TableReception tableReceptionCode = tableReceptionMapper.selectByPrimaryKey(pojo.getId());
    if(tableReceptionCode == null)
    {
      throw new BusinessException(501,"修改数据失败，未找到Id为["+pojo.getId()+"]的数据");
    }
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    BeanUtils.copyProperties(pojo, entity);

    entity.setUpdateDate(new Date());
    entity.setUpdateUserId(adminUser.getAdminUser().getId());
    entity.setUpdateUserName(adminUser.getAdminUser().getUsername());
    tableReceptionMapper.updateByPrimaryKeySelective(entity);
    return entity;
  }

  //编辑数据（更新）
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public TableReception receptionPass(TableReceptionDto pojo)throws BusinessException
  {
    TableReception tableReceptionCode = tableReceptionMapper.selectByPrimaryKey(pojo.getId());
    if(tableReceptionCode == null)
    {
      throw new BusinessException(501,"修改数据失败，未找到Id为["+pojo.getId()+"]的数据");
    }
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    BeanUtils.copyProperties(pojo, entity);

    entity.setUpdateDate(new Date());
    entity.setReceptionOutcome(1l);
    entity.setUpdateUserId(adminUser.getAdminUser().getId());
    entity.setUpdateUserName(adminUser.getAdminUser().getUsername());
    tableReceptionMapper.updateByPrimaryKeySelective(entity);
    return entity;
  }

  //编辑数据（更新）
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public TableReception workDayPass(TableReceptionDto pojo)throws BusinessException
  {
    TableReception tableReceptionCode = tableReceptionMapper.selectByPrimaryKey(pojo.getId());
    if(tableReceptionCode == null)
    {
      throw new BusinessException(501,"修改数据失败，未找到Id为["+pojo.getId()+"]的数据");
    }
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    BeanUtils.copyProperties(pojo, entity);
    entity.setUpdateDate(new Date());
    entity.setPerformAppoint(1l);
    entity.setUpdateUserId(adminUser.getAdminUser().getId());
    entity.setUpdateUserName(adminUser.getAdminUser().getUsername());
    tableReceptionMapper.updateByPrimaryKeySelective(entity);
    return entity;
  }

  //编辑数据（更新）
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public TableReception workNoPass(TableReceptionDto pojo)throws BusinessException
  {
    TableReception tableReceptionCode = tableReceptionMapper.selectByPrimaryKey(pojo.getId());
    if(tableReceptionCode == null)
    {
      throw new BusinessException(501,"修改数据失败，未找到Id为["+pojo.getId()+"]的数据");
    }
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    BeanUtils.copyProperties(pojo, entity);
    entity.setUpdateDate(new Date());
    entity.setPerformAppoint(2l);
    entity.setUpdateUserId(adminUser.getAdminUser().getId());
    entity.setUpdateUserName(adminUser.getAdminUser().getUsername());
    tableReceptionMapper.updateByPrimaryKeySelective(entity);
    return entity;
  }

  //编辑数据（更新）
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public TableReception receptionNoPass(TableReceptionDto pojo)throws BusinessException
  {
    TableReception tableReceptionCode = tableReceptionMapper.selectByPrimaryKey(pojo.getId());
    if(tableReceptionCode == null)
    {
      throw new BusinessException(501,"修改数据失败，未找到Id为["+pojo.getId()+"]的数据");
    }
    AdminUserInToken adminUser = tokenCheckUtil.getUserInfoByToken();
    TableReception entity = new TableReception();
    BeanUtils.copyProperties(pojo, entity);

    entity.setUpdateDate(new Date());
    entity.setReceptionOutcome(2l);
    entity.setUpdateUserId(adminUser.getAdminUser().getId());
    entity.setUpdateUserName(adminUser.getAdminUser().getUsername());
    tableReceptionMapper.updateByPrimaryKeySelective(entity);
    return entity;
  }


  //根据id删除数据
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public Integer delete(String Id)throws BusinessException {
    String arr[] = Id.split(",");
    List<Long> idlist = new ArrayList<>();
    for(int i = 0;i<arr.length;i++){
      Long p = Long.parseLong(arr[i]);
      idlist.add(p);
    }
    if(CollectionUtils.isEmpty(idlist)){
      throw new BusinessException(501, "删除失败，id为null");
    }
    int i = tableReceptionMapper.deleteByIds(idlist);
    if (i<=0){
      throw new BusinessException(501, "删除数据失败");
    }
    return i;
  }

  //根据id删除数据
  @Transactional(propagation= Propagation.REQUIRED,rollbackFor=Exception.class)
  public Integer appRebackReceptionDetail(String Id)throws BusinessException {
    String arr[] = Id.split(",");
    List<Long> idlist = new ArrayList<>();
    for(int i = 0;i<arr.length;i++){
      Long p = Long.parseLong(arr[i]);
      idlist.add(p);
    }
    if(CollectionUtils.isEmpty(idlist)){
      throw new BusinessException(501, "删除失败，id为null");
    }
    int i = tableReceptionMapper.appRebackReceptionDetail(idlist);
    if (i<=0){
      throw new BusinessException(501, "删除数据失败");
    }
    return i;
  }


  //每日预约量
  public List<TableReception> reservationNumber(TableReceptionDto query) throws BusinessException, ParseException {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
      List<TableReception> dbResult = null;
      List<TableReception> dbResultList = new ArrayList<>();
      Calendar calendar=Calendar.getInstance();
      //截取时间
      if(query.getDataTime()!=null){
          String []arr =  query.getDataTime().replaceAll("”","").replaceAll("“","").split(",");
          query.setNowSdate(arr[0].substring(0,10));
          query.setNowEdate(arr[1].substring(0,10));
      }
      if (query.getNowSdate()==null &&query.getNowEdate()==null) {
          calendar.setTime(new Date());
          query.setNowSdate(simpleDateFormat.format(calendar.getTime()));
          calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - 12); // 设置为上12周
          query.setNowSdate(simpleDateFormat.format(calendar.getTime()));
          System.out.println("起始时间"+simpleDateFormat.format(calendar.getTime()));
          query.setNowEdate(simpleDateFormat.format(new Date()));//结束时间
          System.out.println("R"+simpleDateFormat.format(new Date()));
      }

      Date startDate=simpleDateFormat.parse(query.getNowSdate());//起始时间
      Date endDate=simpleDateFormat.parse(query.getNowEdate());//终止时间
      long week = DateUtil.between(startDate,endDate, DateUnit.WEEK);
      System.out.println("周为"+week);
      calendar.setTime(startDate);

      for (int i = 0; i < week ; i++) {
          calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR));
          query.setNowSdate(simpleDateFormat.format(calendar.getTime()));
          System.out.println("这次的起始时间"+simpleDateFormat.format(calendar.getTime()));
          calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) + 1); // 设置为下i周
          query.setNowEdate(simpleDateFormat.format(calendar.getTime()));
          System.out.println("这次的终止时间/下次的起始时间"+simpleDateFormat.format(calendar.getTime()));
          dbResult = tableReceptionMapper.reservationNumber(query);
          if(dbResult.size()>0){
              for (int j = 0; j <dbResult.size() ; j++) {
                  dbResultList.add(dbResult.get(j));
              }
          }

      }
      return dbResultList;
  }
}
